package com.twang.stock.task;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.design.impl.DfcfZhangDieModel;
import com.twang.stock.design.impl.SumTotalTradeAmountTask;
import com.twang.stock.dto.EmailMessage;
import com.twang.stock.entity.DfcfZhangDie;
import com.twang.stock.entity.ZhangTingBan;
import com.twang.stock.mapper.ZhangTingBanMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.rocketMq.RocketMQProducer;
import com.twang.stock.service.CompanyStockMinutesService;
import com.twang.stock.service.ZhangTingBanService;

import com.twang.stock.task.old.BaseTask;
import com.twang.stock.utils.date.DateUtils;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 大盘预警
 */
@Slf4j
@Service
public class DaPanYiDongTask extends BaseTask {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RocketMQProducer rocketMQProducer;

    @Autowired
    private ZhangTingBanService zhangTingBanService;

    @Resource
    private ZhangTingBanMapper zhangTingBanMapper;

    @Resource
    private CompanyStockMinutesService companyStockMinutesService;

    public static String CACHE_KEY_LNQX_DAPANYIDONGTASK = "CACHE_KEY_LNQX_DAPANYIDONGTASK_";


//    @Scheduled(cron = "0 0/1 * * * ?")
    public void excute() {
        if (!isWorkTradeTime()|| DateUtils.JudgeTime("09:25:00", "10:00:00")) {
            return;
        }
        大盘温度预警();
    }

    public void 大盘温度预警() {
        Object obj=redisUtil.get(SumTotalTradeAmountTask.cache_key_LNQX);
        if(null!=obj){
            String key=CACHE_KEY_LNQX_DAPANYIDONGTASK+ HolidayCopy.getRealToday();
            Object objKey=redisUtil.get(key);
            String str="";
            if(null==objKey){
                str = String.format("今日大盘：【%s 】 【成交额：%s亿】",obj,getAmount());
                redisUtil.set(key,obj);
            }else{
                if(!objKey.toString().equals(obj.toString())){
                    str = String.format("大盘异动：大盘由【%s 】 转变成 【%s 】  【成交额：%s亿】",objKey, obj,getAmount());
                    redisUtil.set(key,obj);
                }
            }
            if(StringUtils.isNotEmpty(str)) {
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setCode("000001");
                emailMessage.setName("大盘量能");
                emailMessage.setMessage(str);
                emailMessage.setUserId(Long.valueOf(1));
                emailMessage.setType("1");
                log.info(">>>>>>>>>>> 异动预警 emailMessage={}", JSONObject.toJSONString(emailMessage));
                rocketMQProducer.sendOneWay(JSONObject.toJSONString(emailMessage));
            }
            //TODO 如果量能处于放量，直接监控昨日成交额大票
        }
    }

    /**
     * 预警-严重缩量情况（怼高度）
     */
    private void amountQinXu() {
        String key = "LNQX_" + "_FGQH_" + HolidayCopy.getRealToday();
        Object object = redisUtil.get(key);
        if (null != object) {
            return;
        }
        //TODO 判断量能如果便缩量，开始监控连板的高度板块个股，如果2点之前没有到7000亿，快速预警，如果预警处于放量，那么关闭监控
        if (DateUtils.JudgeTime("13:40:00", "15:00:00")) {
            BigDecimal amount = getAmount();
            if (amount.compareTo(new BigDecimal(7000)) < 1) {
                StringBuffer content = new StringBuffer();
                content.append("<div style='margin-left:4%;font-size:15px;'>");
                content.append("缩量严重，成交额：").append(amount).append("亿").append("，无脑怼高度，昨日最高板如下：");
                {
                    ZhangTingBan param = new ZhangTingBan();
                    param.setDate(companyStockMinutesService.getYesterday());
                    List<ZhangTingBan> zhangTingBanList = zhangTingBanMapper.getYesterDayMax(param);
                    if (CollectionUtils.isNotEmpty(zhangTingBanList)) {
                        content.append(zhangTingBanList.get(0).getLbc()).append("板：");
                        zhangTingBanList.forEach(item -> {
                            content.append("<p style='color:red;font-size:15px;'>");
                            content.append(item.getName());
                            content.append("<a style='color:dark;font-size:10px;'>[").append(item.getHybk()).append("]</a>");
                            content.append("</p>");
                        });
                    }
                }
                content.append("</div>");
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setCode("000001");
                emailMessage.setName("风格切换");
                emailMessage.setMessage(content.toString());
                emailMessage.setUserId(Long.valueOf(1));
                emailMessage.setType("1");
                log.info(">>>>>>>>>>> 异动预警 emailMessage={}", JSONObject.toJSONString(emailMessage));
                rocketMQProducer.sendOneWay(JSONObject.toJSONString(emailMessage));
                redisUtil.set(key, 600);
            }
        }
    }

    public BigDecimal getAmount() {
        try {
            List<DfcfZhangDie> dfcfZhangDies;
            //查询
            Object obj = redisUtil.get(DfcfZhangDieModel.cache_key);
            if (null == obj) {
                dfcfZhangDies = QueryBanKuaiAndDaPan.getDfcfZhangDie();
            } else {
                dfcfZhangDies = JSONObject.parseArray(obj.toString(), DfcfZhangDie.class);
            }
            final BigDecimal[] AtotalAmount = {BigDecimal.ZERO};
            dfcfZhangDies.forEach(item -> {
                AtotalAmount[0] = AtotalAmount[0].add(item.getSzcje());
            });
            BigDecimal amount = AtotalAmount[0].divide(new BigDecimal(100000000)).setScale(2, BigDecimal.ROUND_HALF_UP);
            return amount;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BigDecimal.ZERO;
    }

}
